package daa.levelup.Library;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.List;

public class XmlSerializer {

    public static void Write(List<Book> book) {

        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("Books");
            doc.appendChild(rootElement);

            for (int i = 0; i < book.size(); i++) {
                Book aBook = book.get(i);
                // staff elements
                Element Book = doc.createElement("Library.Book");
                rootElement.appendChild(Book);

                // set attribute to staff element
                Element id = doc.createElement("ID");
                String Id = aBook.getBookId().toString();
                id.appendChild(doc.createTextNode(Id));
                Book.appendChild(id);


                // firstname elements
                Element name = doc.createElement("Name");
                name.appendChild(doc.createTextNode(aBook.getBookName()));
                Book.appendChild(name);


            }

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("D://file.xml"));
            transformer.transform(source, result);

            System.out.println("File saved!");

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }
}